<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>五子棋对战 - 游戏房间</title>
    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/game_room.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
    <div class="nav">
        <div class="logo">
            <i class="fas fa-chess-board"></i>
            <span>五子棋对战平台</span>
        </div>
        <div id="room-status">游戏房间</div>
    </div>

    <div class="container">
        <div class="game-container">
            <div id="chess_area">
                <canvas id="chess" width="450px" height="450px"></canvas>
                <div id="screen">等待玩家连接中...</div>
            </div>
            
            <div id="chat_area">
                <div id="chat_show"></div>
                <div id="msg_show">
                    <input type="text" id="chat_input" placeholder="输入聊天内容...">
                    <button id="chat_button">发送</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 提示弹窗 -->
    <div class="custom-modal" id="infoModal">
        <div class="modal-content">
            <div id="info-content"></div>
            <button class="btn btn-primary" onclick="document.getElementById('infoModal').style.display='none'">确定</button>
        </div>
    </div>

    <script>
        // 棋盘初始化
        const BOARD_ROW_AND_COL = 15;
        let chessBoard = [];
        let chess = document.getElementById('chess');
        let context = chess.getContext('2d');
        
        // WebSocket配置
        const ws_url = "ws://" + location.host + "/room";
        let ws_hdl = new WebSocket(ws_url);
        
        // 房间信息
        let room_info = null;
        let is_me = false; // 是否轮到自己走棋

        // 初始化棋盘数据
        function initBoard() {
            for (let i = 0; i < BOARD_ROW_AND_COL; i++) {
                chessBoard[i] = [];
                for (let j = 0; j < BOARD_ROW_AND_COL; j++) {
                    chessBoard[i][j] = 0;
                }
            }
        }

        // 绘制棋盘网格
        function drawChessBoard() {
            context.strokeStyle = "#8B4513";
            context.lineWidth = 2;
            
            for (let i = 0; i < BOARD_ROW_AND_COL; i++) {
                // 横线
                context.beginPath();
                context.moveTo(15, 15 + i * 30);
                context.lineTo(435, 15 + i * 30);
                context.stroke();
                
                // 竖线
                context.beginPath();
                context.moveTo(15 + i * 30, 15);
                context.lineTo(15 + i * 30, 435);
                context.stroke();
            }
            
            // 绘制天元和星位
            const drawDot = (x, y) => {
                context.beginPath();
                context.arc(x, y, 5, 0, 2 * Math.PI);
                context.fillStyle = "#000";
                context.fill();
            };
            
            drawDot(225, 225); // 天元
            drawDot(75, 75);   // 星位
            drawDot(75, 375);
            drawDot(375, 75);
            drawDot(375, 375);
        }

        // 初始化游戏
        function initGame() {
            initBoard();
            // 加载棋盘背景
            const bg = new Image();
            bg.src = "image/wood-texture.jpg";
            
            // 图片加载成功时绘制背景+网格
            bg.onload = function() {
                context.drawImage(bg, 0, 0, 450, 450);
                drawChessBoard();
            };
            
            // 图片加载失败时直接绘制网格（无背景图）
            bg.onerror = function() {
                console.error("背景图片加载失败，使用默认背景");
                // 浅棕色作为默认背景
                context.fillStyle = "#f0e6d2";
                context.fillRect(0, 0, 450, 450);
                drawChessBoard(); // 强制绘制棋盘线
            };
        }

        // 绘制棋子
        function oneStep(i, j, isWhite) {
            if (i < 0 || j < 0) return;
            
            context.beginPath();
            context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
            context.closePath();
            
            // 棋子立体效果
            const gradient = context.createRadialGradient(
                15 + i * 30 + 2, 15 + j * 30 - 2, 13,
                15 + i * 30 + 2, 15 + j * 30 - 2, 0
            );
            
            if (!isWhite) {
                // 黑棋
                gradient.addColorStop(0, "#0A0A0A");
                gradient.addColorStop(1, "#636766");
            } else {
                // 白棋
                gradient.addColorStop(0, "#D1D1D1");
                gradient.addColorStop(1, "#F9F9F9");
            }
            
            context.fillStyle = gradient;
            context.fill();
            context.strokeStyle = "#333";
            context.stroke();
        }

        // 棋盘点击事件
        chess.onclick = function(e) {
            if (!is_me) {
                showInfo("等待对方走棋...");
                return;
            }
            
            const x = e.offsetX;
            const y = e.offsetY;
            const col = Math.floor(x / 30);
            const row = Math.floor(y / 30);
            
            if (chessBoard[row][col] !== 0) {
                showInfo("当前位置已有棋子!");
                return;
            }
            
            send_chess(row, col);
        }

        // 发送落子请求
        function send_chess(r, c) {
            const chess_info = {
                optype: "put_chess",
                room_id: room_info.room_id,
                uid: room_info.uid,
                row: r,
                col: c
            };
            ws_hdl.send(JSON.stringify(chess_info));
        }

        // 页面关闭前处理
        window.onbeforeunload = function() {
            ws_hdl.close();
        }

        // WebSocket回调
        ws_hdl.onopen = function() {
            console.log("房间长连接建立成功");
        }

        ws_hdl.onclose = function() {
            console.log("房间长连接断开");
            showInfo("连接已断开，即将返回大厅", false, true);
        }

        ws_hdl.onerror = function() {
            console.log("房间长连接出错");
            showInfo("连接出错，请刷新页面重试", false, true);
        }

        // 更新对局状态
        function set_screen(me) {
            const screen = document.getElementById("screen");
            if (me) {
                screen.innerHTML = '<i class="fas fa-chess-pawn"></i> 轮到你走棋';
                screen.style.color = "var(--success)";
            } else {
                screen.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 对方正在思考';
                screen.style.color = "#ffd166";
            }
        }

        // 接收消息处理
        ws_hdl.onmessage = function(evt) {
            try {
                const info = JSON.parse(evt.data);
                console.log("收到房间消息:", info);

                // 房间初始化
                if (info.optype === "room_ready") {
                    room_info = info;
                    is_me = room_info.uid === room_info.white_id;
                    document.getElementById("room-status").textContent = 
                        `房间 ID: ${room_info.room_id} | 你是${is_me ? "白棋" : "黑棋"}`;
                    set_screen(is_me);
                    initGame();
                }

                // 落子处理
                else if (info.optype === "put_chess") {
                    if (!info.result) {
                        showInfo(info.reason || "落子失败");
                        return;
                    }

                    const isWhite = info.uid === room_info.white_id;
                    if (info.row !== -1 && info.col !== -1) {
                        oneStep(info.col, info.row, isWhite);
                        chessBoard[info.row][info.col] = 1;
                    }

                    // 处理胜负
                    if (info.winner !== 0) {
                        const screen = document.getElementById("screen");
                        if (room_info.uid === info.winner) {
                            screen.innerHTML = `<i class="fas fa-trophy"></i> ${info.reason || "恭喜获胜！"}`;
                            screen.style.color = "var(--success)";
                        } else {
                            screen.innerHTML = `<i class="fas fa-meh"></i> 很遗憾，你输了`;
                            screen.style.color = "var(--danger)";
                        }

                        // 添加返回按钮
                        const btn = document.createElement("button");
                        btn.id = "back-button";
                        btn.className = "btn btn-primary";
                        btn.innerHTML = '<i class="fas fa-sign-out-alt"></i> 返回大厅';
                        btn.onclick = function() {
                            ws_hdl.close();
                            location.replace("/game_hall.html");
                        };
                        document.getElementById("chess_area").appendChild(btn);
                        is_me = false; // 游戏结束后不能再落子
                    } else {
                        // 切换回合
                        is_me = info.uid === room_info.uid ? false : true;
                        set_screen(is_me);
                    }
                }

                // 聊天消息
                else if (info.optype === "chat") {
                    if (!info.result) {
                        showInfo(info.reason || "发送失败");
                        return;
                    }

                    const msgDiv = document.createElement("p");
                    msgDiv.textContent = info.message;
                    msgDiv.id = info.uid === room_info.uid ? "self_msg" : "peer_msg";
                    
                    const chatShow = document.getElementById("chat_show");
                    chatShow.appendChild(msgDiv);
                    chatShow.scrollTop = chatShow.scrollHeight; // 滚动到底部
                    
                    // 清空输入框
                    if (info.uid === room_info.uid) {
                        document.getElementById("chat_input").value = "";
                    }
                }
            } catch (e) {
                console.error("消息解析错误:", e);
                showInfo("消息解析失败");
            }
        }

        // 聊天发送
        document.getElementById("chat_button").onclick = function() {
            const input = document.getElementById("chat_input");
            const msg = input.value.trim();
            
            if (!msg) return;
            
            const sendMsg = {
                optype: "chat",
                room_id: room_info?.room_id,
                uid: room_info?.uid,
                message: msg
            };
            
            ws_hdl.send(JSON.stringify(sendMsg));
        }

        // 回车发送聊天
        document.getElementById("chat_input").addEventListener("keypress", function(e) {
            if (e.key === "Enter") {
                document.getElementById("chat_button").click();
            }
        });

        // 显示提示信息
        function showInfo(msg, isSuccess = false, redirect = false) {
            const modal = document.getElementById("infoModal");
            const content = document.getElementById("info-content");
            content.textContent = msg;
            content.style.color = isSuccess ? "var(--success)" : "var(--danger)";
            modal.style.display = "flex";
            
            if (redirect) {
                setTimeout(() => {
                    location.replace("/game_hall.html");
                }, 2000);
            }
        }
    </script>
</body>
</html>